﻿
// 商品车管理ExtJs
function Car_CarInfo() {
    var tbarDeptComboboxValue = "";
    var tbarDeportComboboxValue = "";

    // 定义filters
    var filters = new Ext.ux.grid.GridFilters({
        encode: true,
        filters: [{
            dataIndex: 'Brand', // 品牌
            options: ['丰田', '大众', '本田'],
            //options : TBarDeptStore.collect('Name'),
            type: 'list'
        }]
    });

    //查询语句
    filters.buildQuery = function (filters) {
        var p = {}, i, f, root, dataPrefix, key, tmp, len = filters.length;
        if (!this.encode) {
            for (i = 0; i < len; i++) {
                f = filters[i];
                root = [this.paramPrefix, '[', i, ']'].join('');
                p[root + '[field]'] = f.field;

                dataPrefix = root + '[data]';
                for (key in f.data) {
                    p[[dataPrefix, '[', key, ']'].join('')] = f.data[key];
                }
            }
        } else {
            tmp = [];
            for (i = 0; i < len; i++) {
                f = filters[i];
                tmp.push(Ext.apply({}, {
                    field: f.field
                }, f.data));
            }
            //加上查询条件
            if (tbarDeportComboboxValue != "") {
                tmp.push({
                    field: 'TDeport',
                    type: 'string',
                    value: tbarDeportComboboxValue
                })
            }
            if (tbarDeptComboboxValue != "") {
                tmp.push({
                    field: 'CurrentDep',
                    type: 'string',
                    value: tbarDeptComboboxValue
                })
            }
            // only build if there is active filter
            if (tmp.length > 0) {
                p[this.paramPrefix] = Ext.util.JSON.encode(tmp);
            }
        }
        return p;
    };

    // 机构Combo Store
    var TBarDeptStore = new Infrastructure.NcStore({
        url: '/InfraHospUser/GetDeptList'
    });

    var TBarDeptStore2 = new Infrastructure.DeptJsonStore();

    var TBarDeptStore1 = new Ext.data.JsonStore({
        url: '/InfraHospUser/GetDeptList',
        root: 'data',
        totalProperty: 'total',
        id: 'Id',
        fields: [{
            name: 'Id',
            type: 'string'
        }, {
            name: 'Name',
            type: 'string'
        }, {
            name: 'Code',
            type: 'string'
        }]
    });
	
	//var TBarDeptStore = new Hmis.Util.CommonStore().DEPTSTORE;
	//var TBarDeptStore = new Hmis.Util.DepStore();
	
    TBarDeptStore.load({
        callback: function (r) {
            filters.addFilter({
                type: 'list',
                dataIndex: 'CurrentDep',
                options: JsHelper.GetFilterListData(r, 'Code', 'Name')
            });
        }
    });

    //字典Store
    var DictStore = function (dictCategory) {
        var dictionaryStore = new Infrastructure.DictJsonStore({
            category: dictCategory
        });
        return dictionaryStore;
    }

    var DictStore1 = function (dictCategory) {
        var dictionaryStore = new Ext.data.JsonStore({
            url: '/InfraDictionary/GetPlistByCategoryCode?Code=' + dictCategory,
            root: 'data',
            totalProperty: 'total',
            id: 'Code',
            fields: [{
                name: 'Id',
                type: 'string'
            }, {
                name: 'Name',
                type: 'string'
            }, {
                name: 'Code',
                type: 'string'
            }]
        });
        return dictionaryStore;
    }

    //与筛选有关的字典dictstore
    var DictFilterStore = function (dictCategory, filters, text, value) {
        var dictStore = DictStore(dictCategory);
        dictStore.load({
            callback: function (r) {
                filters.addFilter({
                    type: 'list',
                    dataIndex: dictCategory,
                    options: JsHelper.GetFilterListData(r, value, text)
                });
            }
        });
        return dictStore;
    }

    //总仓Deport Store
    var TDeportStore = DictFilterStore('TDeport', filters, 'Name', 'Name');
    var BrandStore = DictFilterStore('Brand', filters, 'Name', 'Name');
    var ColorStore = DictFilterStore('Color', filters, 'Name', 'Name');
    var ModelStore = DictFilterStore('Model', filters, 'Name', 'Name');

    // 定义表单 商品车信息Reader
    var CarInfoFormReader = new Ext.data.JsonReader({
        root: 'data'
    }, [{
        name: 'TDeport', // 总仓代码
        type: 'string'
    }, {
        name: 'CurrentDep', // 当前展场
        type: 'string'
    }, {
        name: 'Brand', // 品牌代码
        type: 'string'
    }, {
        name: 'Model', // 型号代码
        type: 'string'
    }, {
        name: 'Color', // 颜色代码
        type: 'string'
    }, {
        name: 'Engin_ID', // 发动机号
        type: 'string'
    }, {
        name: 'Frame_ID', // 车架号
        type: 'string'
    }, {
        name: 'Prod_Date', //出厂日期
        type: 'date'
    }, {
        name: 'Miles', //里程
        type: 'int'
    }, {
        name: 'Appraisal', // 估价
        type: 'float'
    }, {
        name: 'Cost', // 成本
        type: 'float'
    }, {
        name: 'VatID', // 增值税发票
        type: 'string'
    }, {
        name: 'Remark', // 备注信息
        type: 'string'
    }, {
        name: 'Atm_GJB', // 附件工具包
        type: 'int'
    }, {
        name: 'Atm_BT', // 附件备胎
        type: 'int'
    }, {
        name: 'Atm_SMS', // 附件说明书
        type: 'int'
    }, {
        name: 'Atm_DYQ', // 附件点烟器
        type: 'int'
    }, {
        name: 'Atm_BXK', // 附件保修卡
        type: 'int'
    }, {
        name: 'Atm_KEY', // 附件车钥匙
        type: 'int'
    }, {
        name: 'Atm_MAST', // 附件雨刮
        type: 'int'
    }, {
        name: 'Atm_CERTIFICATE', // 附件合格证
        type: 'int'
    }, {
        name: 'Sal_CUSTNA', // 销售客户名
        type: 'string'
    }, {
        name: 'Sal_CUSTID', // 销售客户证件号
        type: 'string'
    }, {
        name: 'Sal_CUSTEL', // 销售客户联系方式
        type: 'string'
    }, {
        name: 'Sal_DATE', // 销售日期
        type: 'date'
    }, {
        name: 'Remark', // 备注信息
        type: 'string'
    }]);

    // 定义表格 商品车信息store
    var itemGridStore = new FsCarInfo.Car.JsonStore();

    var itemGridStore1 = new Ext.data.Store({
        url: "/Car/GetPlist",
        remoteSort: true,
        reader: new Ext.data.JsonReader({
            root: 'data',
            totalProperty: 'total',
            id: 'Id'
        }, [{
            name: 'Id',
            type: 'string'// ID
        }, {
            name: 'TDeport', //总仓
            type: 'string'
        }, {
            name: 'CurrentDep', //当前展场
            type: 'string'
        }, {
            name: 'Brand', // 品牌
            type: 'string'
        }, {
            name: 'Model', // 型号
            type: 'string'
        }, {
            name: 'Color', // 颜色
            type: 'string'
        }, {
            name: 'Engin_ID', // 发动机号
            type: 'string'
        }, {
            name: 'Frame_ID', // 车架号
            type: 'string'
        }, {
            name: 'Prod_Date', //出厂日期
            type: 'date'
        }, {
            name: 'Miles', //里程
            type: 'int'
        }, {
            name: 'Appraisal', // 估价
            type: 'float'
        }, {
            name: 'Cost', // 成本
            type: 'float'
        }, {
            name: 'VatID', // 增值税发票
            type: 'string'
        }, {
            name: 'Remark', // 备注信息
            type: 'string'
        }]),
        listeners: {
            'remove': function (thiz, record, index) {
                Ext.Ajax.request({
                    url: '/Car/Delete?Id=' + record.data.Id,
                    success: function (response, opts) {
                        var result = Ext.util.JSON.decode(response.responseText);
                        if (result.success == false) {
                            JsHelper.ShowError(result.msg);
                            itemGridStore.insert(0, record);
                        }
                    }
                });
            }
        }
    });
    itemGridStore.setDefaultSort('TDeport', 'ASC'); // 设置默认排序

    // 定义表格选择方式
    var sm = new Ext.grid.CheckboxSelectionModel();

    // 定义Grid表格列
    var cm = new Ext.grid.ColumnModel([new Ext.grid.RowNumberer(), sm, {
        header: "总仓",
        dataIndex: 'TDeport',
        width: 50,
        sortable: true
    }, {
        header: "展场",
        dataIndex: 'CurrentDep',
        width: 50,
        sortable: true
    }, {
        header: "品牌",
        dataIndex: 'Brand',
        width: 50,
        sortable: true
    }, {
        header: "型号",
        dataIndex: 'Model',
        sortable: true
    }, {
        header: "颜色",
        width: 50,
        dataIndex: 'Color',
        sortable: true
    }, {
        header: "发动机号",
        dataIndex: 'Engin_ID',
        sortable: true
    }, {
        header: "车架号",
        dataIndex: 'Frame_ID',
        sortable: true
    }, {
        header: "出厂日期",
        width: 90,
        dataIndex: 'Prod_Date',
        sortable: true,
        xtype: 'datecolumn',
        format: 'Y年m月d日'
    }, {
        header: "里程",
        width: 40,
        dataIndex: 'Miles',
        align: 'right',
        renderer: Ext.util.Format.numberRenderer('0,0'),
        sortable: true
    }, {
        header: "估价",
        width: 70,
        dataIndex: 'Appraisal',
        align: 'right',
        renderer: Ext.util.Format.numberRenderer('0,0.00'),
        sortable: true
    }, {
        header: "成本",
        width: 70,
        dataIndex: 'Cost',
        align: 'right',
        renderer: Ext.util.Format.numberRenderer('0,0.00'),
        sortable: true
    }, {
        header: "增值税发票",
        width: 80,
        dataIndex: 'VatID',
        sortable: true
    }, {
        header: "备注信息",
        width: 60,
        dataIndex: 'Remark',
        sortable: true
    }]);

    //编辑窗口 todo.
    //var showEditFormWinFn2 = Fs.Car.CarForm(formReader, title, itemGridStore, id );

    var showEditFormWinFn = function (formReader, title, id) {
        var updateEdit = Ext.isDefined(id);
        // 定义获得表单初始加载数据的请求参数
        var formLoadArgs = (updateEdit) ? {
            url: '/Car/GetCarById',
            params: {
                'Id': id
            },
            waitMsg: '数据加载中...'
        } : null;
        //定义表单列
        var firstColumn;
        var secondColumn;

        // 字典字段
        var CarDictCombo = function (desname, dictCategory) {
            return {
                xtype: 'diccombo',
                fieldLabel: desname + '<span style="color: red;" >*</span>',
                name: dictCategory,
                //hiddenName: dictCategory + 'Code',
                store: DictStore(dictCategory),
                mode: 'remote',
                width: 150,
                listWidth: 200
            };
        };

        // 金额字段
        var CnMoneyField = function (in_label, in_name) {
            return new Ext.form.CnMoneyField({
                fieldLabel: in_label,
                name: in_name,
                //fieldClass :'field-align_right x-form-field x-form-num-field',
                width: 150
            });
        };

        var MoneyField_Appraisal = CnMoneyField('估价', 'Appraisal');
        var MoneyField_Cost = CnMoneyField('实际成本', 'Cost');

        var firstColumn = [
			CarDictCombo('总仓', 'TDeport'),
			CarDictCombo('品牌', 'Brand'),
			CarDictCombo('颜色', 'Color'),
			CarDictCombo('型号', 'Model'),
			{
			    fieldLabel: '展场<span style="color: red;" >*</span>',
			    xtype: 'diccombo',
			    name: 'CurrentDep',
			    store: TBarDeptStore,
			    width: 150,
			    listWidth: 200
			}, {
			    fieldLabel: '生产日期',
			    xtype: 'datefield',
			    name: 'Prod_Date',
			    width: 150,
			    format: 'Y年m月d日'
			}
		];

        // 定义表单第二列的组件对象集合
        var secondColumn = [{// 注意 使用时 替换所要表单的第二列组件集合
            fieldLabel: '发动机号<span style="color: red;" >*</span>',
            width: 150,
            name: 'Engin_ID',
            allowBlank: false,
            rvOptions: {
                url: '/Car/IsFieldExist',
                params: {
                    'Id': "-1",
                    'FieldName': 'Engin_ID'
                }
            },
            plugins: [Ext.ux.plugins.RemoteValidator]
        }, {
            fieldLabel: '车架号<span style="color: red;" >*</span>',
            width: 150,
            name: 'Frame_ID',
            allowBlank: false,
            rvOptions: {
                url: '/Car/IsFieldExist',
                params: {
                    'Id': "-1",
                    'FieldName': 'Frame_ID'
                }
            },
            plugins: [Ext.ux.plugins.RemoteValidator]
        }, {
            fieldLabel: '公里数',
            xtype: 'numberfield',
            width: 150,
            name: 'Miles'
        },
		MoneyField_Appraisal,
		MoneyField_Cost,
		{
		    fieldLabel: '增值税号',
		    width: 150,
		    name: 'VatID'
		}];

        // 定义表单单独列的组件对象集合
        var singleColumn = [{
            xtype: 'textarea',
            fieldLabel: '描述',
            name: 'Remark',
            height: 50,
            width: 430
        }];
        // 定义表单 头部固定为两列 末尾单独列 需要改变布局时再修改
        var form = new Ext.FormPanel({
            border: false,
            waitMsgTarget: true,
            labelWidth: 90, // 注意 使用时 如果有表单内组件有特殊标签名称长度很大 替换合适的标签长度
            frame: true,
            bodyStyle: 'padding:5px 5px 0',
            reader: formReader, // 注意 这是传入方法的 Ext.data.DataReader 类型
            // 这里的借用表格store的reader属性
            labelAlign: 'right',
            items: [{
                layout: 'column', // 注意 现在使用的是两列 要是三列或更多
                // 请改变下面的items
                // 并在上面定义每个列的组件集合
                items: [{
                    columnWidth: .5,
                    bodyStyle: 'padding:1px',
                    layout: 'form',
                    defaultType: 'textfield',
                    items: firstColumn
                }, {
                    columnWidth: .5,
                    bodyStyle: 'padding:1px',
                    layout: 'form',
                    defaultType: 'textfield',
                    items: secondColumn
                }]
            }, singleColumn],
            buttonAlign: 'center',
            buttons: [new Ext.ux.SubmitBtn({
                handler: function () {
                    if (form.getForm().isValid()) {
                        form.getForm().submit({
                            url: '/Car/SaveOrUpdate',
                            params: {
                                // 这个地方处理金额取值问题
                                //'Appraisal': MoneyField_Appraisal.getValue(),
                                //'Cost': MoneyField_Cost.getValue(),
                                'Id': (updateEdit) ? id : ""
                            },
                            success: function (form, action) {
                                itemGridStore.setDefaultSort('CreateTime', 'DESC');
                                itemGridStore.load({// 刷新表格
                                    params: {
                                        start: 0,
                                        limit: ALL_PAGESIZE_SETTING
                                    }
                                });
                                win.destroy(); // 关闭窗口
                            },
                            failure: function (form, action) {
                                JsHelper.ShowError(action.result.msg);
                            }
                        }); // formSubmitArgs
                        // 引用之前定义的请求参数变量
                    }
                }
            }), new Ext.ux.CancelBtn({
                handler: function () {
                    win.destroy();
                }
            })]
        });
        // 定义显示窗口
        var win = new Ext.Window({
            title: title,
            iconCls: 'application_form',
            width: 600,
            resizable: false,
            constrain: true,
            autoHeight: true,
            modal: true,
            closeAction: 'close',
            plain: true,
            items: [form]
        });
        win.show();

        //设置值
        form.form.setValues = function (values) {
            if (Ext.isArray(values)) { // array of objects
                for (var i = 0, len = values.length; i < len; i++) {
                    var v = values[i];
                    var f = this.findField(v.id);
                    if (f) {
                        f.setValue(v.value);
                        if (this.trackResetOnLoad) {
                            f.originalValue = f.getValue();
                        }
                    }
                }
            } else { // object hash
                var field, id;
                for (id in values) {
                    if (id == "JobType" && values[id] == "") {
                        continue;
                    }
                    if (!Ext.isFunction(values[id]) && (field = this.findField(id))) {
                        field.setValue(values[id]);
                        if (this.trackResetOnLoad) {
                            field.originalValue = field.getValue();
                        }
                    }
                }
            }
            return this;
        }

        if (formLoadArgs) {
            form.load(formLoadArgs); // formLoadArgs 引用之前定义表单数据加载的请求参数变量
        }
    }
        
    // 定义表格工具栏
    var tbar = [{
        xtype: "tbbutton",
        minWidth: 80,
        ref: '../addBtn',
        text: "添加项",
        cls: "x-btn-text-icon",
        icon: "/Content/icons/add.png",
        handler: function (btn, e) {
            //showEditFormWinFn(CarInfoFormReader, "添加商品车信息");
            Fs.Car.CarForm.showCarEditFormWinFn(CarInfoFormReader, "添加商品车信息", itemGridStore)
        }
    }, "-", {
        xtype: "tbbutton",
        ref: '../delBtn',
        minWidth: 80,
        disabled: true,
        text: "删除项",
        cls: "x-btn-text-icon",
        icon: "/Content/icons/delete.png",
        handler: function (btn, e) {
            JsHelper.DelConfirm(function (btn) {
                if (btn == 'yes') {
                    // gridEditor.stopEditing();
                    var s = grid.getSelectionModel().getSelections();
                    for (var i = 0, r; r = s[i]; i++) {
                        itemGridStore.remove(r);
                    }
                }
            });
        }
    }, "-", {
        xtype: "tbbutton",
        minWidth: 80,
        text: "出库",
        cls: "x-btn-text-icon",
        icon: "/Content/icons/cart_remove.png",
        disabled: true
    }, '-', '总仓:', {
        xtype: 'dictcombo',
        id: 'Car_Grid_TBar_TDeport_Combobox',
        category: 'TDeport'
    }, "-", ' 展场:', {
        xtype: 'deptcombo',
        id: 'Car_Gird_TBar_Dept_Combobox'
    }, '-', {
        xtype: "tbbutton",
        minWidth: 80,
        text: "查询",
        cls: "x-btn-text-icon",
        icon: "/Content/icons/zoom.png",
        handler: function () {
            var tbarDeportCombobox = Ext.getCmp("Car_Grid_TBar_TDeport_Combobox");
            var tbarDeptCombobox = Ext.getCmp("Car_Gird_TBar_Dept_Combobox");
            if (tbarDeptCombobox.getRawValue() != "") {
                tbarDeptComboboxValue = tbarDeptCombobox.getRawValue();
            } else {
                tbarDeptComboboxValue = "";
            }
            if (tbarDeportCombobox.getRawValue() != "") {
                tbarDeportComboboxValue = tbarDeportCombobox.getRawValue();
            } else {
                tbarDeportComboboxValue = "";
            }
            var gridStore = grid.getStore();
            gridStore.load({
                params: {
                    start: 0,
                    limit: ALL_PAGESIZE_SETTING
                }
            });
        }
    }, "-", {
        xtype: "tbbutton",
        minWidth: 80,
        text: "重置",
        cls: "x-btn-text-icon",
        icon: "/Content/icons/arrow_undo.png",
        handler: function () {
            var tbarDeptCombobox = Ext.getCmp("Infra_HospUser_Gird_TBar_Dept_Combobox");
            var tbarRoleIdCombobox = Ext.getCmp("Infra_HospUser_Gird_TBar_Role_Combobox");
            tbarDeptCombobox.clearValue();
            tbarRoleIdCombobox.clearValue();
            tbarDeptComboboxValue = "";
            tbarRoleComboboxValue = "";
            var gridStore = grid.getStore();
            gridStore.reload();
        }
    }];    

    // 分页工具栏
    var bbar = new Ext.PagingToolbar({
        displayInfo: true,
        emptyMsg: "没有数据显示",
        displayMsg: "{0}到{1}条，共{2}条",
        store: itemGridStore,
        pageSize: ALL_PAGESIZE_SETTING,
        plugins: [filters]
    });

    // 商品车信息维护表格
    var grid = new Ext.grid.GridPanel({
        enableColumnMove: false,
        sm: sm,
        cm: cm,
        plugins: [filters],
        stripeRows: true,
        frame: true,
        border: true,
        layout: "fit",
        store: itemGridStore,
        loadMask: true,
        tbar: tbar,
        bbar: bbar,
        listeners: {
            "rowdblclick": function (g, rowIndex, e) {
                var store = g.getStore()
                var id = store.getAt(rowIndex).get("Id");
                //showEditFormWinFn(CarInfoFormReader, "修改商品车信息", id);
                Fs.Car.CarForm.showCarEditFormWinFn(CarInfoFormReader, "商品车信息", itemGridStore, id)
            }
        }
    });

    // 控制删除按钮
    grid.getSelectionModel().on('selectionchange', function (sm) {
        grid.delBtn.setDisabled(sm.getCount() < 1);
    });

    // 加载
    JsHelper.ExtTabDoLayout(grid);
    itemGridStore.load({
        params: {
            start: 0,
            limit: ALL_PAGESIZE_SETTING
        }
    });
};

function CarTest()
{
	JsHelper.ExtTabDoLayout(Fs.Car.CarForm.showCarListGridPanel());
};

function Test2() {
    var carGridStore = new FsCarInfo.Car.JsonStore();
    var gridPanel = new FsCarInfo.Car.GridPanel({
        store: carGridStore
    });
    // 加载
    JsHelper.ExtTabDoLayout(gridPanel);
    carGridStore.load({
        params: {
            start: 0,
            limit: ALL_PAGESIZE_SETTING
        }
    });
};

//CarTest();

//Car_CarInfo();

Test2();